package com.hyy.netty.c2;

import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringEncoder;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;

@Slf4j
public class EventLoopClient {
    public static void main(String[] args) throws InterruptedException {
        /*//1、启动类
        Channel channel = new Bootstrap()
                //2、添加 EventLoop
                .group(new NioEventLoopGroup())
                //3、选择客户端的channel的实现
                .channel(NioSocketChannel.class)
                //4、添加处理器
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override //在连接建立后被调用
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new StringEncoder());

                    }
                })
                //5、连接到服务器
                .connect(new InetSocketAddress("localhost", 8080))
                .sync()//阻塞方法，直到连接建立
                .channel();
        System.out.println(channel);
        System.out.println(111);*/
        ChannelFuture channelFuture = new Bootstrap()
                .group(new NioEventLoopGroup())
                .channel(NioSocketChannel.class)
                .handler(new ChannelInitializer<NioSocketChannel>() {
                    @Override //在连接建立后被调用
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new StringEncoder());

                    }
                })
                //1、连接到服务器
                //异步非阻塞，main 发起了调用，真正调用connect 是 nio 线程
                .connect(new InetSocketAddress("localhost", 8080));
        //2.1 使用sync() 同步处理结果
//        channelFuture.sync();// 阻塞，等到连接建立好后向下执行
//        Channel channel = channelFuture.channel();
//        log.debug("{}",channel);
//        //向服务器发送数据
//        channel.writeAndFlush("hello");
        //2.2 使用addListener(回调对象) 方法异步处理结果
        channelFuture.addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {//连接建立好了，调用此方法
                Channel channel = future.channel();
                log.debug("{}",channel);
                //向服务器发送数据
                channel.writeAndFlush("hello"+System.currentTimeMillis());
            }
        });
    }
}
